'use client'
import React, { useEffect, useState } from 'react'
import { LOCAL_USER, ROUTE_LOGIN } from '@/config/settings';
import { usePathname } from 'next/navigation';
import { useRouter } from 'next/navigation';
import buildPermissionTree from '@/utils/buildPermissionTree';
import Image from 'next/image';

export default function Sider() {
  const [userInfo, setUserInfo] = useState([]);
  const [openMenuId, setOpenMenuId] = useState(null);
  const pathname = usePathname();
  const router = useRouter();
  const [activePath, setActivePath] = useState(pathname);

  useEffect(() => {
    let user = localStorage.getItem(LOCAL_USER);
    if (!user) { return router.push(ROUTE_LOGIN); }
    user = JSON.parse(user) || {};
    const newRole = buildPermissionTree(user?.roleInfo?.permissions);
    setUserInfo(newRole);
    let current = null;
    for (const item of newRole) {
      if (item.path && pathname.startsWith(item.path)) {
        current = item;
        break;
      }
      if (item.children && item.children.length > 0) {
        for (const child of item.children) {
          if (child.path && pathname.startsWith(child.path)) {
            current = item;
            break;
          }
        }
        if (current) break;
      }
    }
    setOpenMenuId(current ? current.id : null);
    setActivePath(pathname);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  const handleMenuClick = (id, path) => {
    if (!path) return;
    setOpenMenuId(id);
    setActivePath(path);
    router.push(path);
  };

  const handleSubMenuClick = (path) => {
    if (!path) return;
    setActivePath(path);
    router.push(path);
  }

  return (
    <div className=' h-[calc(100vh-48px)] overflow-y-scroll scrollbar-hide bg-[#EBEBEB]'>
      <ul className='flex flex-col py-4'>
        {userInfo.length !== 0 && userInfo.map(item => (
          <li onClick={() => item.path && handleMenuClick(item.id)} key={item.id} className="text-sm font-normal text-black cursor-pointer flex flex-col">
            <div onClick={() => handleMenuClick(item.id, item.path)} className={`w-full pl-8 py-3 flex items-center justify-left gap-2 border-l-6 font-medium text-sm ${item.path && activePath.startsWith(item.path) ? 'bg-gradient-to-r from-white to-[#f1f1f11a] text-[var(--theme-color)] border-[var(--theme-color)]' : 'border-l-[#ffffff00]'}`} >
              {item?.icon && (<Image className={`w-4.5 aspect-auto object-contain transition-all duration-300 ${activePath.startsWith(item.path) ? 'filter-focus' : 'filter-unfocus'}`} src={item.icon} alt={item.name} width={360} height={360} />)}
              <span>{item.name}</span>
            </div>
            {item.children && item.children.length > 0 && openMenuId === item.id && (
              <ul className="flex flex-col">
                {item.children.map(subItem => (
                  <li key={subItem.id} className="text-sm text-black cursor-pointer flex font-normal">
                    <div onClick={() => { handleSubMenuClick(subItem.path) }} className={`w-full pl-10 py-3 flex items-center justify-left gap-2 border-l-6 font-medium text-sm ${subItem.path && activePath.startsWith(subItem.path) ? 'bg-gradient-to-r from-white to-[#f1f1f11a] text-[var(--theme-color)] border-[var(--theme-color)]' : 'border-l-[#ffffff00]'}`} >
                      {subItem?.icon && <Image className={`w-4.5 aspect-auto object-contain transition-all duration-300 ${activePath.startsWith(subItem.path) ? 'filter-focus' : 'filter-unfocus'}`} src={subItem.icon} alt={subItem.name} width={360} height={360} />}
                      <span>{subItem.name}</span>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </li>
        ))}
      </ul>
    </div>
  )
}
